﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Awesom_O_Controller
{
    public class D2Multi
    {
        private static readonly string Path = Application.StartupPath + "\\D2Multi\\";

        private static bool CreateNewIni(string diabloPath)
        {
            try
            {
                using (var s = new StreamWriter(Path + "D2Multi.ini", false))
                {
                    s.WriteLine("[Settings]");
                    s.WriteLine("D2Folder = \"" + diabloPath.Remove(diabloPath.LastIndexOf("\\")) + "\\\"");
                    s.Close();
                }
                return true;
            }
            catch (Exception) { Log.Error("Error creating \"D2Multi.ini\""); return false; }
        }

        public static Process StartD2Multi(string diabloPath, string title)
        {
            try
            {
                if (CreateNewIni(diabloPath))
                {
                    var d2MultiProcess = new Process
                                             {
                                                 StartInfo =
                                                     {
                                                         FileName = Path + "D2Multi.exe",
                                                         Arguments = "-w -ns -skiptobnet -title \"" + title + "\"",
                                                         WorkingDirectory = Path,
                                                         UseShellExecute = false
                                                     }
                                             };
                    d2MultiProcess.Start();
                    System.Threading.Thread.Sleep(3000);

                    return Process.GetProcessesByName("game").FirstOrDefault(p => p.MainWindowTitle == title);
                }
                return null;
            }
            catch (Exception e) { Log.Error("D2Multi Error: " + e); return null; }
        }
    }
}
